/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-05-22     甘泽       the first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <drv_common.h>
#include <drivers/pin.h>
#include <drv_spi.h>
#include <sensor.h>
#include <bmm150.h>
#include "sensor/bmm150/sensor_bmm150.h"

static uint8_t bmm150_attach_spi_bus_result = 0;

int rt_bmm150_sensor_register(void)
{
    if (bmm150_attach_spi_bus_result == 0)
    {
        rt_kprintf("sensor bmm150 attach %s, use pin GPIOE-7 failed\n", BMM150_SPI_DEV_NAME);
        return -1;
    }

    rt_kprintf("sensor bmm150 attach %s, use pin GPIOE-7 success\nstart initialize bmm150 sensor\n", BMM150_SPI_DEV_NAME);

    struct rt_sensor_config bmm_cfg;
    bmm_cfg.intf.dev_name = BMM150_SPI_DEV_NAME;
    bmm_cfg.intf.user_data = (void *)BMM150_DEFAULT_I2C_ADDRESS;

    // 使用SPI
    rt_hw_bmm150_init("bmm150", &bmm_cfg, 0);
    rt_thread_mdelay(10);
    return 0;
}
// INIT_APP_EXPORT(rt_bmm150_sensor_register);

// SPI设备需要先注册到SPI总线，即先声明一个片选线
static int bmm150_spi_css(void)
{
    if (rt_hw_spi_device_attach(BMM150_SPI_BUS_NAME, BMM150_SPI_DEV_NAME, GPIOE, GPIO_PIN_7) != RT_EOK)
    {
        return -1;
    }

    bmm150_attach_spi_bus_result = 1;
    return 0;
}
// INIT_COMPONENT_EXPORT(bmm150_spi_css);
